<template>
  <jm-page class="p-12px my-page-menus">
    <div class="flex flex-1">
      <el-row class="h-full w-full">
        <div class="tx-r w-full">
          <el-button type="primary" size="small" @click="addNewMenu"
            >新增菜单</el-button
          >
        </div>
        <el-col :span="24">
        <div class="tree-c">
          <el-tree
            :data="menuDataList"
            node-key="value"
            draggable
            :allow-drop="allowDrop"
            default-expand-all
            @node-drop="handleDrop"
            @node-drag-end="handleDragEnd"
            :expand-on-click-node="false"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span>
                  <el-button
                    type="text"
                    v-if="node.data.menuType === 'menu'"
                    @click="addNewMenu(data)"
                  >
                    添加菜单
                  </el-button>
                  <el-button
                    type="text"
                    v-if="node.data.menuType === 'view'"
                    @click="addNewMenu(data, 'btn')"
                  >
                    添加按钮
                  </el-button>
                  <el-button type="text" @click="edit(data)"> 编辑 </el-button>
                  <el-button
                    type="text"
                    style="margin-left: 8px"
                    :disabled="data.children"
                    @click="remove(node, data)"
                  >
                    删除
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
        </el-col>
      </el-row>
    </div>
  </jm-page>
  <AddOrEditMenu ref="addMenu" @getCurrentMenu="getCurrentMenu" />
  <AddOrEditBtn ref="addBtn" @getCurrentMenu="getCurrentMenu" />
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, onMounted } from 'vue'
import { useAuthority } from '@/views/Authority/authorityCom.js'
import AddOrEditMenu from './components/addOrEditMenu.vue'
import AddOrEditBtn from './components/addOrEditBtn.vue'
import { getCurrentMenuApi } from '@/api/modules/authority.js'
import { deleteMenuApi, deleteBtnApi, moveMenu } from '@/api/modules/menu.js'
const modules = useAuthority()
const addMenu = ref(null)
const addBtn = ref(null)
const addNewMenu = (data, btn) => {
  if (btn === 'btn') {
    if (addBtn.value) {
      addBtn.value.dialogVisible = true
      addBtn.value.title = '新增按钮'
      addBtn.value.ruleForm.parentId = data.value
    }
    return
  }
  if (addMenu.value) {
    Object.assign(addMenu.value.ruleForm, {
      name: '', // 菜单名
      address: '', // 访问地址
      compent: '', // 对应的页面地址
      parentId: 0, // 父id，可选填，默认顶级节点0
      menuType: 'menu', // 菜单类型：menu，view，bottom，只能填这三个
      stat: 'ENABLE', // 状态，非必参，可选填：ENABLE启用，DISABLE禁用，默认启用
      remark: '', // 说明，非必参
      icoUrl: ''
    })
    addMenu.value.squareUrl = null
    addMenu.value.dialogVisible = true
    addMenu.value.title = '新增菜单'
    addMenu.value.ruleForm.parentId = data.value
  }
}
const edit = data => {
  const mendata = JSON.parse(JSON.stringify(data))
  mendata.name = mendata.label
  mendata.stat = 'ENABLE'
  mendata.id = mendata.value
  delete mendata.children
  delete mendata.label
  delete mendata.value
  if (mendata.menuType === 'bottom') {
    if (addBtn.value) {
      addBtn.value.dialogVisible = true
      addBtn.value.title = '编辑按钮'
      setTimeout(() => {
        Object.assign(addBtn.value.ruleForm, mendata)
      }, 100)
    }
    return
  }
  if (addMenu.value) {
    addMenu.value.dialogVisible = true
    addMenu.value.title = '编辑菜单'
    setTimeout(() => {
      Object.assign(addMenu.value.ruleForm, mendata)
      addMenu.value.squareUrl = mendata.icoUrl
    }, 100)
  }
}
const menuDataList = ref([])
const menuDataListCopy = ref([])
const getCurrentMenu = async () => {
  const { data } = await getCurrentMenuApi()
  menuDataList.value = data
  menuDataListCopy.value = JSON.parse(JSON.stringify(data))
}
const remove = node => {
  let name = '目录'
  if (node.data.menuType === 'menu') {
    name = '目录'
  }
  if (node.data.menuType === 'view') {
    name = '菜单'
  }
  if (node.data.menuType === 'bottom') {
    name = '按钮'
  }
  ElMessageBox.confirm(`确认要删除当前${name}吗?`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // console.log(node, 11111)
    deleteMenu(node.data.value)
  })
}
const deleteMenu = async id => {
  const { data } = await deleteMenuApi(id)
  getCurrentMenu()
}
const deleteBtn = async id => {
  const { data } = await deleteBtnApi(id)
  getCurrentMenu()
}

const allowDrop = (dropNode, Node, type) => {
  return type !== 'inner'
}
const handleDragEnd = (draggingNode, dropNode, event) => {
  console.log(draggingNode, 111111)
  console.log(dropNode, 222222)
  if (draggingNode.level !== dropNode.level) {
    menuDataList.value = JSON.parse(JSON.stringify(menuDataListCopy.value))
    return
  }
  const params = {
    "id": draggingNode.data.value,            // 必参，选中行的id
    "newIndex":event === 'after' ? dropNode.data.orderNo : dropNode.data.orderNo - 1,       // 必参，新的下标（想要拖拽到哪里去）
    "parentId":dropNode.data.parentId,       // 必参，选中行的父id
    "direction":event === 'after' ? 'down' : 'up'    // 必参，拖拽方位，只能填up 或 down
  }
  moveMenuApi(params)
}
const moveMenuApi = async(params) => {
  const {msg} = await moveMenu(params)
  if (msg === 'ok') {
    getCurrentMenu()
  }
} 

onMounted(() => {
  getCurrentMenu()
})
</script>
<style>
.my-page-menus .el-tree-node__content {
  border-bottom: 1px solid #ebeef5;
  padding: 4px 0;
  height: 40px;
}
</style>
<style lang="scss" scoped>
.tx-r {
  text-align: right;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-tree-node__content {
  border-bottom: 1px solid #d6d8dd;
}
.el-tree {
  border: 1px solid #d6d8dd;
  border-bottom: 0;
  margin-top: 20px;
}
.tree-c {
  overflow: auto;
  height: 82vh;
}
</style>
